package org.zxb.calllocalservice.loadbalancer;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClients;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * 开发环境负载均衡配置；
 * 仅在使用 LoadBalancer 作为负载均衡组件与 Nacos 作为注册中心时生效。
 * 不同于之前的使用修改请求地址的实现，这里通过重新实现负载均衡策略，获取请求的源 ip 地址，并将请求发往源 ip 地址。
 *
 * @author zxb
 * @date 2022-08-22 11:09
 **/

@Configuration
@ConditionalOnDiscoveryEnabled
@LoadBalancerClients(defaultConfiguration = {DevLoadbalancerConfig.class})
@Log4j2
public class DevLoadbalancerConfig {

    @Bean
    @ConditionalOnClass(value = {LoadBalancerClientFactory.class, NacosDiscoveryProperties.class})
    @ConditionalOnProperty(prefix = "router.call-local", name = "enable", havingValue = "true")
    ReactorLoadBalancer<ServiceInstance> devLoadbalancerLoadBalancer(Environment environment,
                                                            LoadBalancerClientFactory loadBalancerClientFactory,
                                                            NacosDiscoveryProperties nacosDiscoveryProperties) {
        if (log.isInfoEnabled()) {
            log.info("开启负载均衡至本地服务");
        }
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        ObjectProvider<ServiceInstanceListSupplier> lazyProvider =
                loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class);
        return new DevLoadBalanceRuleLoadBalancer(lazyProvider, name, nacosDiscoveryProperties);
    }
}
